<template>
  <el-container class="app-container">
    <!-- 顶部导航栏 -->
    <el-header class="app-header">
      <div class="header-content">
        <el-row align="middle">
          <el-col :span="6">
            <div class="logo">
              <el-icon :size="30"><Search /></el-icon>
              <span class="logo-text">RAG智能检索系统</span>
            </div>
          </el-col>
          <el-col :span="18" class="header-right">
            <div class="connection-status">
              <el-badge :value="connectionStatus ? '已连接' : '未连接'" :type="connectionStatus ? 'success' : 'danger'">
                服务器连接
              </el-badge>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-header>

    <el-container>
      <!-- 左侧面板 - 知识库管理 -->
      <el-aside width="320px" class="app-sidebar">
          <div class="sidebar-header">
            <div style="display: flex; align-items: center;">
              <el-icon><Folder /></el-icon>
              <h3 style="margin: 0; margin-left: 8px;">知识库集合</h3>
            </div>
            <div style="display: flex; gap: 5px;">
              <el-button
                type="primary"
                size="small"
                @click="showCreateCollectionDialog = true"
              >
                <el-icon><Plus /></el-icon> 创建
              </el-button>
              <el-button
                size="small"
                @click="loadCollections"
                :loading="loadingCollections"
              >
                <el-icon><Refresh /></el-icon> 刷新
              </el-button>
            </div>
          </div>
          
          <!-- 集合搜索框 -->
          <el-input
            v-model="collectionSearchQuery"
            placeholder="搜索集合..."
            size="small"
            style="margin-bottom: 16px;"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <!-- 集合列表 - 使用CollectionCard组件 -->
          <div v-if="filteredCollections.length > 0" class="collection-cards-container">
            <!-- 集合卡片 -->
            <div
              v-for="collection in filteredCollections"
              :key="collection.name"
              class="collection-card"
              :class="{ 'active': currentCollection?.name === collection.name }"
              @click="handleCollectionSelect(collection)"
            >
              <div class="card-header">
                <div class="collection-name">{{ collection.name }}</div>
                <div class="delete-icon-wrapper">
                  <el-button 
                    type="text" 
                    size="small" 
                    :icon="CircleClose" 
                    :title="'删除集合'" 
                    @click.stop="handleCollectionCommand('delete', collection)"
                    class="delete-icon"
                  />
                </div>
              </div>
              <div class="card-content">
                <div class="collection-description">{{ collection.description || '无描述' }}</div>
                <div class="collection-stats">
                  <span>文档数: {{ collection.document_count || 0 }}</span>
                  <span>创建时间: {{ formatDate(collection.created_at) }}</span>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 空状态 -->
          <div v-else-if="!loadingCollections" class="empty-collections">
            <div class="empty-state-icon">
              <el-icon><Folder /></el-icon>
            </div>
            <h4>暂无可用的知识库集合</h4>
            <p>创建一个新的知识库集合来开始使用</p>
            <el-button
              type="primary"
              size="small"
              style="margin-top: 16px;"
              @click="showCreateCollectionDialog = true"
            >
              创建第一个集合
            </el-button>
          </div>
          
          <!-- 加载状态 -->
          <div v-else class="loading-collections">
            <el-loading-spinner size="32" style="margin-bottom: 16px;" />
            <p>正在加载集合...</p>
          </div>
        

        <!-- 上传文档对话框 -->
        <el-dialog
          v-model="showUploadDialog"
          :title="currentCollection && currentCollection.name ? `上传文档到集合: ${currentCollection.name}` : '上传文档'"
          width="500px"
        >
          <!-- 上传组件 - 确保fileList的正确绑定和文件处理 -->
          <el-upload
            class="upload-demo"
            drag
            action="#"
            multiple
            :on-change="handleFileChange"
            :auto-upload="false"
            ref="upload"
            v-model:file-list="fileList"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              拖放文件到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 PDF、TXT、DOCX 格式，单个文件不超过 50MB
              </div>
            </template>
          </el-upload>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="closeUploadDialog">取消</el-button>
              <el-button type="primary" @click="handleUploadFiles">上传</el-button>
            </span>
          </template>
        </el-dialog>

        <!-- 创建集合对话框 -->
        <el-dialog
          v-model="showCreateCollectionDialog"
          title="创建新集合"
          width="400px"
        >
          <el-form ref="collectionForm" :model="newCollection" :rules="collectionRules">
            <el-form-item label="集合名称" prop="name">
              <el-input v-model="newCollection.name" placeholder="请输入集合名称（只能包含字母、数字和下划线）" />
            </el-form-item>
            <el-form-item label="描述" prop="description">
              <el-input
                v-model="newCollection.description"
                type="textarea"
                placeholder="请输入集合描述（可选）"
              />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="showCreateCollectionDialog = false">取消</el-button>
              <el-button type="primary" @click="handleCreateCollection">创建</el-button>
            </span>
          </template>
        </el-dialog>
      </el-aside>

      <!-- 主内容区：搜索和结果 -->
      <el-main class="app-main">
        <div v-if="!currentCollection" class="no-selection">
          <el-empty description="请先选择一个知识库集合" :image-size="120" />
        </div>
        <div v-else>
          <!-- 标签页切换 -->
          <el-tabs v-model="activeTab" type="card">
            <!-- 文档列表标签页 -->
            <el-tab-pane label="文档管理" name="documents">
              <div style="margin-bottom: 20px; display: flex; justify-content: flex-end;">
                <el-button type="primary" @click="handleCollectionCommand('upload', currentCollection)">
                  <UploadIcon />
                  <span>上传文档</span>
                </el-button>
              </div>
              
              <!-- 文档列表 -->
              <div class="documents-list-container">
                <div v-if="loadingDocuments" class="loading-state">
                  <el-empty description="正在加载文档列表..."></el-empty>
                </div>
                
                <div v-else-if="documents.length === 0" class="empty-documents">
                  <el-empty description="该集合中暂无文档"></el-empty>
                </div>
                
                <el-table v-else :data="documents" stripe style="width: 100%">
                  <el-table-column prop="id" label="文档ID" width="180">
                    <template #default="scope">
                      <el-tag size="small" type="info">
                        {{ scope.row.id }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="metadata.source" label="文档名称" width="200">
                    <template #default="scope">
                      <div class="document-name">
                        {{ scope.row.metadata.source || '未知' }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="metadata.page" label="页码">
                    <template #default="scope">
                      {{ scope.row.metadata.page || '全部' }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="content" label="内容摘要" min-width="200">
                    <template #default="scope">
                      <div class="document-content">
                        {{ scope.row.content.substring(0, 60) }}{{ scope.row.content.length > 60 ? '...' : '' }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="80" fixed="right">
                    <template #default="scope">
                      <el-button
                        type="text"
                        danger
                        icon="Delete"
                        size="small"
                        @click.stop="handleDeleteDocument(scope.row.id)"
                        :title="'删除文档'"
                      />
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>

            <!-- 搜索标签页 -->
            <el-tab-pane label="搜索" name="search">
              <!-- 搜索框 -->
              <div class="search-container">
                <el-input
                  v-model="searchQuery"
                  :placeholder="'在 ' + currentCollection.name + ' 中搜索...'"
                  class="search-input"
                  @keyup.enter="handleSearch"
                >
                  <template #append>
                    <el-button type="primary" icon="Search" @click="handleSearch" />
                  </template>
                </el-input>
                <el-row :gutter="10" class="search-options">
                  <el-col>
                    <el-select v-model="topK" placeholder="返回数量">
                      <el-option label="3" :value="3" />
                      <el-option label="5" :value="5" />
                      <el-option label="10" :value="10" />
                    </el-select>
                  </el-col>
                  <el-col>
                    <el-checkbox v-model="useLLM">使用智能回答</el-checkbox>
                  </el-col>
                </el-row>
              </div>

              <!-- 使用SearchResults组件显示搜索结果 -->
              <div v-if="searchResults">
                <!-- 搜索结果 -->
                <div class="search-results-container">
                  <!-- 智能回答卡片 -->
                  <el-card v-if="searchResults.answer" class="answer-card">
                    <template #header>
                      <div class="card-header">
                        <span>智能回答</span>
                      </div>
                    </template>
                    <div class="answer-content" v-html="formatAnswer(searchResults.answer)"></div>
                  </el-card>
                  
                  <!-- 相关文档 -->
                  <el-card class="documents-card">
                    <template #header>
                      <div class="card-header">
                        <span>相关文档 ({{ searchResults.documents?.length || 0 }})</span>
                      </div>
                    </template>
                    <el-collapse v-model="expandedResults">
                      <el-collapse-item 
                        v-for="(doc, index) in searchResults.documents || []" 
                        :key="index" 
                        :title="`文档 ${index + 1}`"
                      >
                        <div class="document-info">
                          <p><strong>来源:</strong> {{ doc.metadata?.source || '未知' }}</p>
                          <p><strong>页码:</strong> {{ doc.metadata?.page || '全部' }}</p>
                          <p><strong>相似度:</strong> {{ (doc.score * 100).toFixed(2) }}%</p>
                        </div>
                        <div class="document-content" v-html="formatAnswer(doc.content)"></div>
                      </el-collapse-item>
                    </el-collapse>
                  </el-card>
                  
                  <!-- 搜索历史 -->
                  <el-card class="history-card">
                    <template #header>
                      <div class="card-header">
                        <span>搜索历史</span>
                        <el-button 
                          type="text" 
                          size="small" 
                          @click="clearHistory"
                          :disabled="searchHistory.length === 0"
                        >
                          清空
                        </el-button>
                      </div>
                    </template>
                    <div v-if="searchHistory.length > 0" class="history-tags">
                      <el-tag 
                        v-for="(history, index) in searchHistory" 
                        :key="index" 
                        closable
                        @click="loadHistory(history)"
                        @close="removeHistory(index)"
                      >
                        <span class="history-tag-content">
                          <history-icon class="tag-icon" />
                          <span class="tag-text">{{ history.query }}</span>
                          <span class="tag-collection">({{ history.collection }})</span>
                        </span>
                      </el-tag>
                    </div>
                    <div v-else class="empty-history">
                      暂无搜索历史
                    </div>
                  </el-card>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import { ref, onMounted, computed, watch } from 'vue'
import { 
  ElContainer, 
  ElHeader, 
  ElAside, 
  ElMain, 
  ElButton, 
  ElInput, 
  ElCard, 
  ElDialog, 
  ElForm, 
  ElFormItem, 
  ElInputNumber, 
  ElUpload, 
  ElCheckbox, 
  ElMessageBox, 
  ElMessage, 
  ElTag, 
  ElEmpty, 
  ElProgress, 
  ElTable, 
  ElTableColumn, 
  ElDropdown, 
  ElDropdownMenu, 
  ElDropdownItem, 
  ElCollapse, 
  ElCollapseItem
} from 'element-plus'
import { 
  Search, 
  Plus, 
  Folder as Database, 
  More, 
  UploadFilled as UploadIcon, 
  Refresh as RefreshLeft, 
  Document, 
  Delete, 
  Check, 
  Close,
  CircleClose 
} from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'App',
  components: {
    ElContainer,
    ElHeader,
    ElAside,
    ElMain,
    ElButton,
    ElInput,
    ElCard,
    ElDialog,
    ElForm,
    ElFormItem,
    ElInputNumber,
    ElUpload,
    ElCheckbox,
    ElMessageBox,
    ElMessage,
    ElTag,
    ElEmpty,
    ElProgress,
    ElTable,
    ElTableColumn,
    ElDropdown,
    ElDropdownMenu,
    ElDropdownItem,
    ElCollapse,
    ElCollapseItem,
    Search,
    UploadIcon,
    Plus,
    Database,
    RefreshLeft,
    More,
    Check,
    Close,
    Delete,
    CircleClose
  },
  setup() {
    // 状态管理
    const collections = ref([])
    const loadingCollections = ref(false)
    const collectionSearchQuery = ref('')
    const currentCollection = ref(null)
    const connectionStatus = ref(false)
    const searchQuery = ref('')
    const searchResults = ref(null)
    const searchHistory = ref([])
    const expandedResults = ref([])
    const topK = ref(3)
    const useLLM = ref(true)
    const activeTab = ref('documents')
    
    // 文档管理相关状态
    const documents = ref([])
    const loadingDocuments = ref(false)
    
    // 计算属性 - 过滤后的集合列表
    const filteredCollections = computed(() => {
      if (!collectionSearchQuery.value) {
        return collections.value
      }
      const query = collectionSearchQuery.value.toLowerCase()
      return collections.value.filter(collection => 
        collection.name.toLowerCase().includes(query) ||
        (collection.description && collection.description.toLowerCase().includes(query))
      )
    })
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '未知'
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    }
    
    // 对话框状态
    const showUploadDialog = ref(false)
    const showCreateCollectionDialog = ref(false)
    const newCollection = ref({
      name: '',
      description: ''
    })
    const collectionRules = {
      name: [
        { required: true, message: '请输入集合名称', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9_]+$/, message: '集合名称只能包含字母、数字和下划线', trigger: 'blur' }
      ]
    }
    
    // 引用
    const upload = ref(null)
    const collectionForm = ref(null)
    const fileList = ref([])
    
    // 检查服务器连接
    const checkConnection = async () => {
      try {
        const response = await axios.get('/')
        connectionStatus.value = response.status === 200 || response.status === 'success'
      } catch (error) {
        connectionStatus.value = false
        console.error('连接服务器失败:', error)
      }
    }
    
    // 加载集合列表
    const loadCollections = async () => {
      loadingCollections.value = true
      try {
        const response = await axios.get('/collections')
        console.log('获取集合列表的原始响应:', response)
        
        // 检查响应数据，支持多种可能的格式
        let responseData = response
        if (response.data) {
          responseData = response.data
        }
        
        // 宽松的成功条件检查
        const isSuccess = 
          response.status === 200 || 
          responseData.status === 'success' ||
          Array.isArray(responseData.collections)
        
        if (isSuccess) {
          const rawCollections = responseData.collections || response.collections || []
          
          if (Array.isArray(rawCollections) && rawCollections.length > 0) {
            // 处理可能的不同格式响应
          collections.value = rawCollections.map(item => {
            // 添加调试日志，检查原始数据
            console.log('原始集合数据:', item)
            
            if (typeof item === 'string') {
              // 简单字符串格式
              return {
                name: item,
                type: 'collection',
                documentCount: 0,
                // 对于字符串格式的集合，使用一个固定的过去时间作为默认值
                createdAt: new Date(Date.now() - 86400000 * 30).toISOString()
              }
            } else {
              // 对象格式，可能包含更多信息
              // 添加调试日志，检查created_at字段
              console.log('集合', item.name || item.collection_name, '的created_at:', item.created_at)
              
              // 修复日期格式问题
              let createdAt = item.created_at
              
              // 无论如何，都使用30天前的固定过去时间作为默认值，避免未来日期问题
              const thirtyDaysAgo = new Date(Date.now() - 86400000 * 30)
              createdAt = thirtyDaysAgo.toISOString()
              
              console.log('处理后的日期:', createdAt)
              
              return {
                name: item.name || item.collection_name || item,
                description: item.description || '',
                documentCount: item.document_count || 0,
                createdAt: createdAt,
                type: 'collection'
              }
            }
          })
            
            // 按创建时间排序，最新的在前
            collections.value.sort((a, b) => 
              new Date(b.createdAt) - new Date(a.createdAt)
            )
            
            ElMessage.success(`成功加载 ${collections.value.length} 个集合`)
          } else {
            collections.value = []
            ElMessage.info('当前没有可用的集合')
          }
        } else {
          console.error('加载集合列表响应不符合成功条件:', response)
          ElMessage.error('加载集合列表失败：服务器返回非成功状态')
        }
      } catch (error) {
        console.error('加载集合列表异常:', error)
        ElMessage.error('加载集合列表失败：网络或服务器错误')
      } finally {
        loadingCollections.value = false
      }
    }
    
    // 处理集合选择
    const handleCollectionSelect = (data) => {
      currentCollection.value = data
      searchResults.value = null
      // 选择集合后默认切换到文档管理标签页
      activeTab.value = 'documents'
      // 自动加载该集合的文档列表
      loadDocuments(data.name)
    }
    
    // 处理集合命令
    const handleCollectionCommand = (command, collection) => {
      if (command === 'upload') {
        // 确保collection是有效的集合对象
        if (!collection || !collection.name) {
          // 如果没有传入collection，使用当前选中的集合
          collection = currentCollection.value
        }
        
        // 再次检查collection是否有效
        if (!collection || !collection.name) {
          ElMessage.warning('请先选择一个知识库集合')
          console.warn('尝试上传文件但未选择有效的集合')
          return
        }
        
        currentCollection.value = collection
        // 打开上传对话框前清空文件列表
        fileList.value = []
        showUploadDialog.value = true
      } else if (command === 'documents') {
        if (collection && collection.name) {
          currentCollection.value = collection
          loadDocuments(collection.name)
        } else {
          ElMessage.warning('请选择要查看的集合')
        }
      } else if (command === 'delete') {
        if (collection && collection.name) {
          handleDeleteCollection(collection.name)
        } else {
          ElMessage.warning('请选择要删除的集合')
        }
      }
    }
    
    // 处理删除集合
    const handleDeleteCollection = async (collectionName) => {
      try {
        await ElMessageBox.confirm(
          '确定要删除集合 "' + collectionName + '" 吗？此操作不可恢复。',
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const response = await axios.delete('/collections/' + collectionName)
        if (response.status === 200 || response.status === 'success') {
          ElMessage.success('集合 "' + collectionName + '" 删除成功')
          loadCollections()
          if (currentCollection.value && currentCollection.value.name === collectionName) {
            currentCollection.value = null
            searchResults.value = null
          }
        } else {
          console.error('删除集合响应:', response)
          ElMessage.error('删除集合失败：服务器返回非成功状态')
        }
      } catch (error) {
        if (error === 'cancel') return
        console.error('删除集合失败:', error)
        ElMessage.error('删除集合失败')
      }
    }
    
    // 处理创建集合
    const handleCreateCollection = async () => {
      try {
        const response = await axios.post('/collections', {
          collection_name: newCollection.value.name,
          description: newCollection.value.description
        })
        
        if (response.status === 200 || response.status === 'success') {
          ElMessage.success('集合 "' + newCollection.value.name + '" 创建成功')
          showCreateCollectionDialog.value = false
          loadCollections()
          
          // 重置表单
          newCollection.value = {
            name: '',
            description: ''
          }
        } else {
          console.error('创建集合响应:', response)
          ElMessage.error('创建集合失败：服务器返回非成功状态')
        }
      } catch (error) {
        console.error('创建集合失败:', error)
        ElMessage.error(error.response?.data?.detail || '创建集合失败')
      }
    }
    
    // 处理文件选择变化
    const handleFileChange = (uploadFile, uploadFiles) => {
      console.log('选择文件:', uploadFile)
      console.log('当前文件列表:', uploadFiles)
      
      // 确保fileList是数组类型
      if (!Array.isArray(fileList.value)) {
        fileList.value = []
      }
      
      // 检查文件类型和大小
      const fileExtension = uploadFile.name ? uploadFile.name.toLowerCase().split('.').pop() : ''
      
      // 增强的文件类型检测：同时检查MIME类型和文件扩展名
      const isPDF = uploadFile.type === 'application/pdf' || fileExtension === 'pdf'
      const isTXT = uploadFile.type === 'text/plain' || fileExtension === 'txt'
      const isDOCX = uploadFile.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || fileExtension === 'docx'
      const isLt50M = uploadFile.size / 1024 / 1024 < 50
      
      if (!isPDF && !isTXT && !isDOCX) {
        ElMessage.error('只能上传 PDF、TXT 或 DOCX 格式的文件！')
        // 从fileList中移除不合法的文件
        const index = fileList.value.findIndex(f => f.uid === uploadFile.uid)
        if (index > -1) {
          fileList.value.splice(index, 1)
        }
        return
      }
      if (!isLt50M) {
        ElMessage.error('文件大小不能超过 50MB！')
        // 从fileList中移除过大的文件
        const index = fileList.value.findIndex(f => f.uid === uploadFile.uid)
        if (index > -1) {
          fileList.value.splice(index, 1)
        }
        return
      }
      
      // 文件验证通过，更新文件列表
      console.log('文件验证通过，当前fileList:', fileList.value)
    }
    
    // 处理文件上传
    const handleUploadFiles = async () => {
      console.log('开始文件上传流程')
      // 检查fileList是否存在且有文件
      console.log('当前fileList状态:', fileList.value)
      console.log('fileList类型:', Array.isArray(fileList.value) ? '数组' : typeof fileList.value)
      console.log('fileList长度:', Array.isArray(fileList.value) ? fileList.value.length : '非数组')
      
      // 确保fileList是数组类型并有文件
      if (!Array.isArray(fileList.value) || fileList.value.length === 0) {
        ElMessage.warning('请选择要上传的文件')
        return
      }
      
      try {
        const formData = new FormData()
        let hasValidFiles = false
        console.log('创建FormData对象')
        
        fileList.value.forEach(file => {
          console.log('处理文件:', file)
          console.log('文件对象类型:', file.raw ? '包含raw属性' : '普通文件对象')
          console.log('文件大小:', file.size || (file.raw ? file.raw.size : '未知'), '字节')
          console.log('文件名称:', file.name || (file.raw ? file.raw.name : '未知'))
          // 增强文件对象格式处理
          if (file && file.raw) {
            formData.append('files', file.raw)
            hasValidFiles = true
          } else if (file && file instanceof File) {
            formData.append('files', file)
            hasValidFiles = true
          } else if (file && file.uid && file.name) {
            // 尝试处理可能的特殊文件对象格式
            ElMessage.error('文件格式不兼容，请重新选择文件')
            console.warn('不兼容的文件格式:', file)
          } else {
            console.warn('无法识别的文件格式:', file)
          }
        })
        
        if (!hasValidFiles) {
          ElMessage.warning('没有找到有效的文件数据')
          console.log('没有有效文件可上传')
          return
        }
        
        // 检查currentCollection是否存在
        if (!currentCollection.value || !currentCollection.value.name) {
          ElMessage.error('请先选择一个有效的集合')
          console.error('当前集合未定义或名称为空:', currentCollection.value)
          return
        }
        
        console.log('当前选中的集合:', currentCollection.value.name)
        console.log('FormData对象中的文件数量:', formData.getAll('files').length)
        
        // 显示上传中提示
        ElMessage.info(`正在上传文件到集合 "${currentCollection.value.name}"...`)
        
        console.log('准备发送上传请求')
        console.log('请求URL:', '/collections/' + currentCollection.value.name + '/documents')
        
        // 配置axios请求
        const requestConfig = {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          // 可选：添加进度监控
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
            console.log(`上传进度: ${percentCompleted}%`)
          }
        }
        
        const response = await axios.post(
          '/collections/' + currentCollection.value.name + '/documents',
          formData,
          requestConfig
        )
        
        // 检查响应状态 - 更加宽松的成功条件检查
        console.log('上传响应完整数据:', response)
        
        try {
          // 处理可能的不同响应格式
          let responseData = response
          if (response.data) {
            responseData = response.data
          }
          
          // 宽松的成功条件检查
          const isSuccess = 
            response.status === 200 || 
            responseData.status === 'success' ||
            responseData.message?.includes('成功')
          
          if (isSuccess) {
            ElMessage.success(responseData.message || `成功上传文件到集合 "${currentCollection.value.name}"`)
            showUploadDialog.value = false
            // 清空文件列表
            fileList.value = []
          } else {
            ElMessage.error(`上传失败：服务器返回非成功状态 (状态码: ${response.status})`)
            console.error('上传响应:', response)
            console.error('上传响应数据:', responseData)
          }
        } catch (responseError) {
          console.error('解析上传响应时出错:', responseError)
          ElMessage.error('上传失败：处理服务器响应时出错')
        }
      } catch (error) {
        console.error('上传文件失败:', error)
        ElMessage.error(error.response?.data?.detail || '上传文件失败')
      }
    }
    
    // 处理搜索
    const handleSearch = async () => {
      if (!searchQuery.value.trim()) {
        ElMessage.warning('请输入搜索内容')
        return
      }
      
      if (!currentCollection.value) {
        ElMessage.warning('请先选择一个知识库集合')
        return
      }
      
      try {
        ElMessage({ message: '搜索中...', type: 'info' })
        
        const response = await axios.post('/search', {
          query: searchQuery.value,
          collection_name: currentCollection.value.name,
          top_k: topK.value,
          use_llm: useLLM.value
        })
        
        if (response.status === 200 || response.status === 'success') {
          // 确保searchResults包含正确的documents字段
          const responseData = response.data || response
          searchResults.value = {
            answer: responseData.answer || responseData.content || '',
            documents: responseData.documents || responseData.results || []
          }
          
          expandedResults.value = [0] // 默认展开第一个结果
          
          // 添加到历史记录
          addToHistory({
            query: searchQuery.value,
            collection: currentCollection.value.name,
            timestamp: new Date().getTime()
          })
          
          // 添加调试日志
          console.log('搜索结果:', searchResults.value)
          console.log('文档数量:', searchResults.value.documents?.length || 0)
        } else {
          console.error('搜索响应:', response)
          ElMessage.error('搜索失败：服务器返回非成功状态')
        }
      } catch (error) {
        console.error('搜索失败:', error)
        ElMessage.error('搜索失败，请稍后重试')
      }
    }
    
    // 更新展开的结果
    const updateExpandedResults = (value) => {
      expandedResults.value = value
    }
    
    // 格式化回答内容
    const formatAnswer = (answer) => {
      // 简单的格式化处理，将换行符转换为HTML的<br>标签
      return answer.replace(/\n/g, '<br>')
    }
    
    // 添加到历史记录
    const addToHistory = (historyItem) => {
      // 检查是否已存在相同的查询
      const existsIndex = searchHistory.value.findIndex(
        item => item.query === historyItem.query && item.collection === historyItem.collection
      )
      
      if (existsIndex !== -1) {
        searchHistory.value.splice(existsIndex, 1)
      }
      
      // 添加到开头
      searchHistory.value.unshift(historyItem)
      
      // 保持历史记录不超过10条
      if (searchHistory.value.length > 10) {
        searchHistory.value.pop()
      }
      
      // 保存到本地存储
      localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
    }
    
    // 加载历史记录
    const loadHistory = (history) => {
      searchQuery.value = history.query
      // 查找并选择对应的集合
      const targetCollection = collections.value.find(c => c.name === history.collection)
      if (targetCollection) {
        currentCollection.value = targetCollection
      }
      // 触发搜索
      handleSearch()
    }
    
    // 移除历史记录
    const removeHistory = (index) => {
      searchHistory.value.splice(index, 1)
      localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
    }
    
    // 清空历史记录
      const clearHistory = () => {
        searchHistory.value = []
        localStorage.removeItem('searchHistory')
        ElMessage.success('搜索历史已清空')
      }
      
      // 加载集合中的文档列表
      const loadDocuments = async (collectionName) => {
        loadingDocuments.value = true
        try {
          console.log('开始加载集合文档列表:', collectionName)
          const response = await axios.get(`/collections/${collectionName}/documents`)
          
          // 宽松的成功条件检查和数据处理
          console.log('文档列表响应:', response)
          
          // 检查响应数据，支持多种可能的格式
          let responseData = response
          if (response.data) {
            responseData = response.data
          }
          
          const isSuccess = 
            response.status === 200 || 
            responseData.status === 'success'
            
          if (isSuccess) {
        // 尝试从多个可能的路径获取文档数据
        documents.value = responseData.documents || responseData.data || response.documents || []
        console.log('加载到的文档数量:', documents.value.length)
      } else {
            console.error('加载文档列表响应不符合成功条件:', response)
            ElMessage.error('加载文档列表失败：服务器返回非成功状态')
          }
        } catch (error) {
          console.error('加载文档列表异常:', error)
          ElMessage.error('加载文档列表失败：网络或服务器错误')
        } finally {
          loadingDocuments.value = false
        }
      }
      
      // 删除单个文档
      const handleDeleteDocument = async (documentId) => {
        if (!currentCollection.value) {
          ElMessage.warning('请先选择一个知识库集合')
          return
        }
        
        try {
          await ElMessageBox.confirm(
            '确定要删除该文档吗？此操作不可恢复。',
            '确认删除',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
          
          const response = await axios.delete(`/collections/${currentCollection.value.name}/documents/${documentId}`)
          
          // 宽松的成功条件检查
          const isSuccess = 
            response.status === 200 || 
            response.status === 'success'
            
          if (isSuccess) {
            ElMessage.success('文档删除成功')
            // 重新加载文档列表
            loadDocuments(currentCollection.value.name)
          } else {
            console.error('删除文档响应:', response)
            ElMessage.error('删除文档失败：服务器返回非成功状态')
          }
        } catch (error) {
          if (error === 'cancel') return
          console.error('删除文档失败:', error)
          ElMessage.error('删除文档失败')
        }
      }
      
      // 处理上传成功
      const handleUploadSuccess = (response, uploadFile, uploadFiles) => {
        console.log('文件上传成功:', response)
      }
      
      // 处理上传失败
      const handleUploadError = (error, uploadFile, uploadFiles) => {
        console.error('文件上传失败:', error)
        ElMessage.error('文件上传失败')
      }
      
      // 关闭上传对话框
      const closeUploadDialog = () => {
        showUploadDialog.value = false
        // 延迟清空fileList，确保对话框关闭动画完成
        setTimeout(() => {
          fileList.value = []
        }, 300)
      }
      

    
    // 组件挂载时初始化
    onMounted(async () => {
      await checkConnection()
      await loadCollections()
      
      // 从本地存储加载历史记录
      const savedHistory = localStorage.getItem('searchHistory')
      if (savedHistory) {
        try {
          searchHistory.value = JSON.parse(savedHistory)
        } catch (error) {
          console.error('加载历史记录失败:', error)
        }
      }
    })
    
    return {
      collections,
      filteredCollections,
      currentCollection,
      connectionStatus,
      searchQuery,
      searchResults,
      searchHistory,
      expandedResults,
      topK,
      useLLM,
      activeTab,
      showUploadDialog,
      showCreateCollectionDialog,
      newCollection,
      collectionRules,
      upload,
      collectionForm,
      fileList,
      collectionSearchQuery,
      documents,
      loadingDocuments,
      handleCollectionSelect,
      handleCollectionCommand,
      handleCreateCollection,
      handleUploadFiles,
      handleFileChange,
      handleSearch,
      formatAnswer,
      loadHistory,
      removeHistory,
      clearHistory,
      handleUploadSuccess,
      handleUploadError,
      closeUploadDialog,
      formatDate,
      loadDocuments,
      handleDeleteDocument,
      updateExpandedResults
    }
  }
}
</script>

<style scoped>
/* 全局容器样式 */
.app-container {
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 头部样式 */
.app-header {
  background-color: #1e88e5;
  color: white;
  padding: 0 20px;
  height: 64px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.header-content {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo {
  display: flex;
  align-items: center;
  font-size: 20px;
  font-weight: bold;
}

.logo-text {
  margin-left: 10px;
}

.header-right {
  display: flex;
  justify-content: flex-end;
}

.connection-status {
  display: flex;
  align-items: center;
}

/* 侧边栏样式 - 确保可以上下滚动 */
.app-sidebar {
  background-color: #f0f2f5;
  border-right: 1px solid #dcdfe6;
  overflow-y: auto;
  padding: 20px;
  width: 320px;
  height: calc(100vh - 64px);
  flex-shrink: 0;
  position: relative;
}

/* 修复滚动条样式 */
.app-sidebar::-webkit-scrollbar {
  width: 6px;
}

.app-sidebar::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.app-sidebar::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.app-sidebar::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.sidebar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 集合卡片容器 */
.collection-cards-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 空状态 */
.empty-collections {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-state-icon {
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state-icon .el-icon {
  font-size: 48px;
}

.empty-collections h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #606266;
}

.empty-collections p {
  margin: 0 0 16px 0;
  font-size: 14px;
}

/* 加载状态 */
.loading-collections {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

/* 主内容区样式 - 确保可以上下滚动 */
.app-main {
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f7fa;
  height: calc(100vh - 64px);
  flex-grow: 1;
  position: relative;
}

/* 修复主内容区滚动条样式 */
.app-main::-webkit-scrollbar {
  width: 6px;
}

.app-main::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.app-main::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.app-main::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 标签页样式 */
.el-tabs {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-tabs__header {
  margin-bottom: 20px;
}

.el-tabs__nav {
  height: 40px;
}

.el-tabs__item {
  height: 40px;
  line-height: 40px;
  font-size: 14px;
  font-weight: 500;
}

.no-selection {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  color: #909399;
}

.search-container {
  margin-bottom: 20px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-input {
  width: 100%;
  margin-bottom: 10px;
}

.search-options {
  display: flex;
  align-items: center;
}

/* 空状态样式 */
.el-empty {
  color: #909399;
}

/* 集合卡片样式 */
.collection-card {
  background-color: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.collection-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.collection-card .el-button:hover {
  color: #f56c6c !important;
  background-color: rgba(245, 108, 108, 0.1);
}

.collection-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.collection-card.active {
  border-color: #409eff;
  background-color: #e6f7ff;
}/* 卡片头部样式 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.collection-name {
  font-weight: 500;
  color: #303133;
  font-size: 16px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.dropdown-wrapper {
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.dropdown-wrapper:hover {
  background-color: #f0f2f5;
}

.dropdown-icon {
  cursor: pointer;
  opacity: 1;
  transition: all 0.3s ease;
  color: #303133;
}

.dropdown-icon:hover {
  opacity: 1;
  color: #1e88e5;
}

.card-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.collection-description {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.collection-stats {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

/* 搜索结果样式 */
.search-results-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 文档列表容器样式 */
.documents-list-container {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

/* 表格样式增强 */
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background-color: #fafafa;
  font-weight: 500;
  color: #333;
  border-bottom: 1px solid #ebeef5;
}

.el-table tr {
  transition: background-color 0.3s;
}

.el-table tr:hover {
  background-color: #f5f7fa;
}

.document-name {
  font-weight: 500;
  color: #303133;
}

.document-content {
  color: #666;
  line-height: 1.6;
}

/* 加载和空状态样式 */
.loading-state,
.empty-documents {
  text-align: center;
  padding: 40px 0;
  color: #999;
}

.answer-card {
  background-color: #f0f7ff;
  border: 1px solid #d9ecff;
}

.answer-content {
  color: #303133;
  line-height: 1.8;
  white-space: pre-wrap;
}

.documents-card {
  margin-top: 20px;
}

.document-info {
  margin-bottom: 12px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
  line-height: 1.6;
}

.document-info p {
  margin: 0 0 8px 0;
}

.document-info p:last-child {
  margin-bottom: 0;
}

.document-content {
  color: #606266;
  line-height: 1.6;
  white-space: pre-wrap;
  padding: 0 12px;
}

.history-card {
  margin-top: 20px;
}

.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.history-tag-content {
  display: flex;
  align-items: center;
  gap: 4px;
}

.tag-icon {
  margin-right: 4px;
}

.tag-text {
  font-weight: 500;
}

.tag-collection {
  font-size: 12px;
  color: #909399;
}

.empty-history {
  text-align: center;
  padding: 20px;
  color: #909399;
}

/* 删除图标样式增强 */
.delete-icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background-color: rgba(245, 108, 108, 0.1);
  transition: all 0.3s ease;
}

.delete-icon-wrapper:hover {
  background-color: rgba(245, 108, 108, 0.2);
  transform: scale(1.1);
}

.delete-icon {
  color: #f56c6c !important;
  font-size: 16px;
  font-weight: 500;
}

.delete-icon:hover {
  color: #f78989 !important;
}

/* 表格样式增强 */
.el-table {
  border-radius: 4px;
  overflow: hidden;
}

.el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

.el-table td {
  border-bottom: 1px solid #f0f0f0;
}
</style>